package demo.cfg;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;

import io.micrometer.core.instrument.Counter;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.Selector;
import org.springframework.boot.actuate.endpoint.annotation.WriteOperation;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Endpoint(id = "super")
public class SuperEndPoint {
    private Map<String, SuperUser> users = new ConcurrentHashMap<>();

    @ReadOperation
    public Set<String> users() {
        Counter.builder("users").register().increment();
        return users.keySet();
    }

    @ReadOperation
    public SuperUser usersIdentify(@Selector String arg0) {
        return users.get(arg0);
    }

    @WriteOperation
    public Set<String> set(String userName, String passwd) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        if (request != null) {
            SuperUser superUser = new SuperUser();
            superUser.setUserName(userName);
            superUser.setPasswd(passwd);
            request.getSession().setAttribute("superUser", superUser);

            users.put(superUser.getUserName(), superUser);
        }

        return users.keySet();
    }

    public static class SuperUser {
        private String userName;
        private String passwd;

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }

        public String getPasswd() {
            return passwd;
        }

        public void setPasswd(String passwd) {
            this.passwd = passwd;
        }
    }
}